import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import router from '@/router'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // baseURL: 'http://ihrm-java.itheima.net', // 设置axios请求的基础的基础地址
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    const { token } = store.state.user
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(

  response => {
    // 如果登陆成功,返回想要的数据
    if (response.data.success) {
      return response.data
    } else {
      // 如果账号或密码错误,将错误信息返回并抛出
      Message({
        message: response.data.message,
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(new Error(response.data.message))
    }
  },
  error => {
    // 失效 token 处理
    if (error.response && error.response.data && error.response.data.code === 10002) {
      // 清除 token 和用户资料,跳转登录页
      store.dispatch('user/logout')
      router.replace('/login')
      // 过期提示
      return Message({
        message: '登录过期,请重新登陆!',
        type: 'error',
        duration: 5 * 1000
      })
    }
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
